package main

import (
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
	"github.com/spf13/pflag"
	"github.com/spf13/viper"
	"riceguess_backend/internal/repository"
	"riceguess_backend/internal/repository/cache"
	"riceguess_backend/internal/service"
	"riceguess_backend/internal/web"
	"strings"
)

func InitViper() {
	// 读取启动参数
	s := pflag.String("config", "config/dev.yaml", "配置文件路径")
	pflag.Parse()
	// 设置配置文件路径
	viper.SetConfigFile(*s)
	// 读取配置
	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}
}

func main() {
	InitViper()
	server := gin.Default()
	// 解决跨域问题
	server.Use(cors.New(cors.Config{
		AllowCredentials: true,                                      // 允许携带cookie
		AllowHeaders:     []string{"Content-Type", "authorization"}, // 请求头
		AllowMethods:     []string{"POST", "GET"},                   // 请求方法
		ExposeHeaders:    []string{"x-jwt-token"},                   // 允许前端获取的请求头信息
		AllowOriginFunc: func(origin string) bool {
			return strings.HasPrefix(origin, "http://localhost")
		},
	}))
	client := redis.NewClient(&redis.Options{
		Addr: viper.GetString("redis.addr"),
	})
	answerCache := cache.NewRedisAnswerCache(client)
	answerRepository := repository.NewCachedAnswerRepository(answerCache)
	aiService := service.NewDefaultAIService(answerRepository)
	aiHandler := web.NewAIHandler(aiService)
	aiHandler.RegisterRoutes(server)
	server.Run(":8080")
}
